package com.smasher.dialog.select.adapter

import android.util.Log
import android.util.SparseIntArray
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.util.size
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import com.smasher.dialog.R
import com.smasher.dialog.select.delegate.ElementShowDelegate
import com.smasher.dialog.select.delegate.SelectDelegate
import com.smasher.dialog.select.SelectMode

class SelectPageAdapter<T : Any>(
    private var elementShowDelegate: ElementShowDelegate<T>,
    diffCallback: DiffUtil.ItemCallback<T>
) : PagingDataAdapter<T, SelectViewHolder<T>>(diffCallback) {

    var mode: SelectMode = SelectMode.SINGLE
        set(value) {
            field = value
            delegate.mode = value
        }

    private var delegate = object : SelectDelegate(mode) {
        override fun notifyAdapterItemChanged(sparseIntArray: SparseIntArray) {
            for (i in 0 until sparseIntArray.size) {
                val index = sparseIntArray.keyAt(i)
                notifyItemChanged(index)
            }

        }
    }

    override fun onCreateViewHolder(
        p0: ViewGroup,
        p1: Int
    ): SelectViewHolder<T> {
        val inflater = LayoutInflater.from(p0.context)
        val view = inflater.inflate(R.layout.item_select_base, p0, false)
        return SelectViewHolder(view)
    }

    override fun onBindViewHolder(
        p0: SelectViewHolder<T>,
        p1: Int
    ) {
        val item = getItem(p1) ?: return
        Log.d(TAG, "onBindViewHolder: $p1")
        p0.setElementShowDelegate(elementShowDelegate)
        p0.setSelected(delegate.isSelected(p1))
        p0.setOnSingleSelectListener(delegate)
        p0.setIndex(p1)
        p0.setItem(item)
        p0.bindView()
    }


    fun getSelectList(): ArrayList<T> {
        val selectedArray = delegate.selectedArray
        val selectList = ArrayList<T>()
        for (i in 0 until selectedArray.size) {
            val index = selectedArray.keyAt(i)
            val item = getItem(index)
            if (item != null) {
                selectList.add(item)
            }
        }
        return selectList
    }

    companion object {
        const val TAG = "PageAdapter"
    }
}